//
//  MapViewController.m
//  A段项目
//
//  Created by 刘言松 on 15/10/16.
//  Copyright (c) 2015年 刘言松. All rights reserved.
//

#import "MapViewController.h"
#import "MKAnnotation.h"
#import "dayModel.h"
#import "daysModel.h"
#import "TravelDetailViewController.h"
#import "PhotoAnnotationView.h"
#import <UIImageView+WebCache.h>

@interface MapViewController ()<MKMapViewDelegate>

@property (nonatomic)CLLocationCoordinate2D begin_coordinate;
@property (nonatomic)CLLocationCoordinate2D coordinate;
@property (nonatomic, retain)UIButton *btn;
@property (nonatomic, retain)UIButton *pushBtn;
@property (nonatomic, assign)BOOL flag;
@property (nonatomic, retain)UIView *photoView;
@property (nonatomic, retain)UIImageView *imageView;
@property (nonatomic, retain)UIImageView *bgView;
@property (nonatomic, retain)MKAnnotation *tmpAnno;
@end

@implementation MapViewController

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    
    
    [self.tabBarController.tabBar setHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.coordinate = CLLocationCoordinate2DMake(0, 0);
    
    self.annoArray = [NSMutableArray array];
    [self setMap];
    [self addNextAndPreBtn];
 
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIImage *image = [UIImage imageNamed:@"add_new_poi_back_btn"];
    UIImage *img = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(pop)];
    self.navigationItem.leftBarButtonItem = left;
}

- (void)addNextAndPreBtn{
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextBtn setImage:[UIImage imageNamed:@"trip_map_fullscreen_next_button@2xpng"] forState:UIControlStateNormal];
    nextBtn.frame = CGRectMake(WIDTH *0.6, HEIGHT*0.75, WIDTH *0.2, HEIGHT*0.1);
    nextBtn.layer.masksToBounds = YES;
    nextBtn.layer.cornerRadius = nextBtn.height/2;
    nextBtn.backgroundColor = [UIColor blackColor];
    nextBtn.alpha = 0.5;
    [nextBtn addTarget:self action:@selector(next) forControlEvents:UIControlEventTouchUpInside];
    
    [self.map addSubview:nextBtn];
    
    UIButton *preBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [preBtn setImage:[UIImage imageNamed:@"trip_map_fullscreen_previous_button"] forState:UIControlStateNormal];
    preBtn.frame = CGRectMake(WIDTH *0.2, HEIGHT*0.75, WIDTH *0.2, HEIGHT*0.1);
    preBtn.layer.masksToBounds = YES;
    preBtn.layer.cornerRadius = preBtn.height/2;
    preBtn.backgroundColor = [UIColor blackColor];
    preBtn.alpha = 0.5;
    [preBtn addTarget:self action:@selector(pre) forControlEvents:UIControlEventTouchUpInside];
    
    [self.map addSubview:preBtn];
    
    UIButton *playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [playBtn setImage:[UIImage imageNamed:@"trip_map_fullscreen_play_button"] forState:UIControlStateNormal];
    playBtn.frame = CGRectMake(WIDTH *0.4, HEIGHT*0.75, WIDTH *0.2, HEIGHT*0.1);
    playBtn.layer.masksToBounds = YES;
    playBtn.layer.cornerRadius = playBtn.height/2;
    playBtn.backgroundColor = [UIColor blackColor];
    playBtn.alpha = 0.5;
    [playBtn addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.map addSubview:playBtn];
}

- (void)play:(UIButton *)btn{
    if (self.isPlay) {
        [self.timer invalidate];
        self.timer = nil;
        [btn setImage:[UIImage imageNamed:@"trip_map_fullscreen_play_button"]forState:UIControlStateNormal];
    }
    else{
      self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(next) userInfo:nil repeats:YES];
         [btn setImage:[UIImage imageNamed:@"trip_map_fullscreen_pause_button"]forState:UIControlStateNormal];
    }
    self.isPlay = !self.isPlay;
}

- (void)next{
    if (self.current<self.annoArray.count-1) {
        self.current++;
        [self showPhoto:self.current];
    }
}

- (void)pre{
    if (self.current>0) {
        self.current--;
        [self showPhoto:self.current];
    }
}

- (void)showPhoto:(NSInteger)current{
    NSLog(@"%@",self.annoArray);
    
    dayModel *day = [self.annoArray objectAtIndex:current];
    
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([day.latitude floatValue], [day.longitude floatValue]);
    
  
        [self.map setCenterCoordinate:coordinate];
     
        [self addPhotoAnnotation:day Current:current];
}

- (UIView *)addPhotoView:(NSString *)imageUrl{
    
    if (self.photoView != nil) {
        
        [self.photoView removeFromSuperview];
        
    }
    self.photoView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH*0.5, WIDTH*0.35)];
    

    
    self.bgView = [[UIImageView alloc]initWithFrame:self.photoView.bounds];
    self.bgView.image = [UIImage imageNamed:@"trip_map_callout_bg"];
    [self.photoView addSubview:self.bgView];

    
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.bgView.width *0.92, self.bgView.height * 0.9)];
    self.imageView.center = CGPointMake(self.bgView.width/2, self.bgView.height/2 - self.bgView.height*0.03);
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"place_holder_cell"]];
    [self.bgView addSubview:self.imageView];

    
    self.pushBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.pushBtn.frame = self.photoView.bounds;
    [self.pushBtn addTarget:self action:@selector(pushDetail) forControlEvents:UIControlEventTouchUpInside];
    [self.photoView addSubview:self.pushBtn];
    return self.photoView;
    

}




-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
    
    MKAnnotation *anno = (MKAnnotation *)view.annotation;
    
    self.current = anno.current;
    
    [self addPhotoAnnotation:[self.annoArray objectAtIndex:self.current]  Current:self.current];
}


- (void)addPhotoAnnotation:(dayModel *)day Current:(NSInteger)current{

    MKAnnotation *anno = [[MKAnnotation alloc]init];
    
    anno.coordinate = CLLocationCoordinate2DMake([day.latitude floatValue], [day.longitude floatValue]);
    anno.category = [day.category stringValue];
    anno.current = current;
    
    [self.map addAnnotation:anno];
    

}

- (void)addAnnotation:(dayModel *)day Current:(NSInteger)current{
    NSString *pre_latitude = [NSString stringWithFormat:@"%.2f", self.coordinate.latitude];
    NSString *pre_longitude = [NSString stringWithFormat:@"%.2f", self.coordinate.longitude];
    NSString *day_latitude = [NSString stringWithFormat:@"%.2f", [day.latitude floatValue]];
    NSString *day_longitude = [NSString stringWithFormat:@"%.2f", [day.longitude floatValue]];
    
    if (![pre_latitude isEqualToString:day_latitude] && ![pre_longitude isEqualToString:day_longitude]) {
      
        MKAnnotation *anno = [[MKAnnotation alloc]init];
        anno.coordinate = CLLocationCoordinate2DMake([day.latitude floatValue], [day.longitude floatValue]);
        anno.category = [day.category stringValue];
        anno.current = current;
        [self.map addAnnotation:anno];
        

    }
    
    if (self.coordinate.longitude != 0 && self.coordinate
        .latitude != 0) {
        
        
        CLLocationCoordinate2D pathCoords[2] =
        {
            self.coordinate,
            CLLocationCoordinate2DMake([day.latitude floatValue], [day.longitude floatValue])
        };
        
        MKPolyline *pathOverlay = [MKPolyline polylineWithCoordinates:pathCoords count:2];
        
        
        
        [self.map addOverlay:pathOverlay];
    }
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    
    PhotoAnnotationView *annoView = [[PhotoAnnotationView alloc]initWithAnnotation:nil reuseIdentifier:nil];
 
    MKAnnotation *myAnnotation = (MKAnnotation *)annotation;
    
    dayModel *day = [self.annoArray objectAtIndex:myAnnotation.current];
    
    UIView *tmpView = [self addPhotoView:day.photo];
    tmpView.center = CGPointMake(annoView.width/2 + WIDTH * 0.02 , 0);
    tmpView.y = annoView.y - tmpView.height - annoView.height;
    
    [annoView addSubview:tmpView];

    if (myAnnotation.category.length == 0) {
        annoView.image = [UIImage imageNamed:@"map_text"];
    }
    else{
        NSString *imageName = [NSString stringWithFormat:@"annotation_%@",myAnnotation.category];
        annoView.image = [UIImage imageNamed:imageName];
    }
    
    return annoView;
}


- (void)setMap{
    
    self.map = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64)];
    self.map.mapType = MKMapTypeStandard;
    self.map.delegate = self;
    [self.view addSubview:self.map];

    
    NSInteger current = 0;
    
    for (int i = 0; i<self.daysArray.count; i++) {
        
        daysModel *days = [self.daysArray objectAtIndex:i];
        for (int j = 0; j < days.waypoints.count;j++) {
            
            dayModel *day = [days.waypoints objectAtIndex:j];
            if (day.latitude != nil) {
                
                if (current == 0) {
                    self.begin_coordinate = CLLocationCoordinate2DMake([day.latitude floatValue], [day.longitude floatValue]);
                }
                [self addAnnotation:day Current:current];
                [self.annoArray addObject:day];
                
                self.coordinate = CLLocationCoordinate2DMake([day.latitude floatValue], [day.longitude floatValue]);
               
                current++;
            }
        }
    }
    
    MKCoordinateSpan span = MKCoordinateSpanMake(0.45, 0.3);
    MKCoordinateRegion region = MKCoordinateRegionMake(self.begin_coordinate,span);
    [self.map setRegion:region animated:YES];
}


-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
    if ([overlay isKindOfClass:[MKPolyline class]])
    {
        MKPolylineRenderer *renderer=[[MKPolylineRenderer alloc]initWithOverlay:overlay];
        renderer.strokeColor=MBCOLOR;
        renderer.lineWidth=1.0;
        return renderer;
    }
    return nil;
}

- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{
    
    }

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    [self.map removeFromSuperview];
    [self.view addSubview:mapView];
}

- (void)pop{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
